package com.xysq.util;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;

import com.alipay.sdk.app.PayTask;
import com.flyco.animation.BaseAnimatorSet;
import com.flyco.animation.FadeExit.FadeExit;
import com.flyco.animation.FlipEnter.FlipVerticalSwingEnter;
import com.flyco.dialog.listener.OnBtnClickL;
import com.flyco.dialog.widget.NormalTipDialog;
import com.tencent.mm.sdk.modelpay.PayReq;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.xysq.XYApplication;
import com.xysq.activity.BaseActivity;
import com.xysq.activity.CustomerPayActivity;
import com.xysq.activity.MyOrderActivity;
import com.xysq.lemon.R;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.security.InvalidKeyException;
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.SignatureException;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.util.LinkedList;
import java.util.List;
import java.util.Random;

/**
 * Created by huangdongkai on 2015/9/30.
 */
public class PayUtil extends BaseActivity {
    //微信支付
    public void genSign(String prepayId, Context context) {
        PayReq req = new PayReq();
        req.appId = "wxbebea3d7ddadbea6";
        req.partnerId = "1264396601";
        req.prepayId = prepayId;
        req.packageValue = "Sign=WXPay";
        req.nonceStr = genNonceStr();
        req.timeStamp = String.valueOf(System.currentTimeMillis());
        List<NameValuePair> signParams = new LinkedList<NameValuePair>();
        signParams.add(new BasicNameValuePair("appid", req.appId));
        signParams.add(new BasicNameValuePair("noncestr", req.nonceStr));
        signParams.add(new BasicNameValuePair("package", req.packageValue));
        signParams.add(new BasicNameValuePair("partnerid", req.partnerId));
        signParams.add(new BasicNameValuePair("prepayid", req.prepayId));
        signParams.add(new BasicNameValuePair("timestamp", req.timeStamp));
        req.sign = genAppSign(signParams);
        IWXAPI msgApi = XYApplication.getWXAPI();
        msgApi.registerApp(PropertiesUtil.getAppWechatKey());
        if (isWXAppInstalledAndSupported(msgApi, context)) {
            msgApi.sendReq(req);
        }
    }

    private boolean isWXAppInstalledAndSupported(IWXAPI api, Context context) {
        boolean sIsWXAppInstalledAndSupported = api.isWXAppInstalled()
                && api.isWXAppSupportAPI();
        if (!sIsWXAppInstalledAndSupported) {
            ToastUtil.showShort(context, "微信客户端未安装，请确认");
        }

        return sIsWXAppInstalledAndSupported;
    }

    //生成签名
    private String genAppSign(List<NameValuePair> params) {
        StringBuilder sb = new StringBuilder();

        for (int i = 0; i < params.size(); i++) {
            sb.append(params.get(i).getName());
            sb.append('=');
            sb.append(params.get(i).getValue());
            sb.append('&');
        }
        sb.append("key=");
        sb.append(PropertiesUtil.getAppSecret());
        String appSign = MD5.getMessageDigest(sb.toString().getBytes()).toUpperCase();
        return appSign;
    }

    private String genNonceStr() {
        Random random = new Random();
        return MD5.getMessageDigest(String.valueOf(random.nextInt(10000)).getBytes()).toUpperCase();
    }
    //微信支付END

    //支付宝支付
    private static final String ALGORITHM = "RSA";
    private static final String SIGN_ALGORITHMS = "SHA1WithRSA";
    private static final String DEFAULT_CHARSET = "UTF-8";
    private static final int MESSAGE_ALIPAY = 0;
    private String payInfo;
    private Activity activity;
    private boolean mResult = false;
    private int orderId;
    private int couponModelId;
    private String word;
    private CustomerPayActivity customerPayActivity;

    public void alipay(int orderId,String word, String orderNumber,int couponModelId, String name, String introduction, String price, Context context, boolean result) {
        activity = (Activity) context;
        this.orderId = orderId;
        this.couponModelId = couponModelId;
        this.word = word;
        mResult = result;
        String orderInfo = createAlipayInfo(orderNumber, name, introduction, price);
        String sign = sign(orderInfo);
        try {
            // 仅需对sign 做URL编码
            sign = URLEncoder.encode(sign, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        payInfo = orderInfo + "&sign=\"" + sign + "\"&"
                + getSignType();

        new Thread(new AlipayRunnable()).start();
    }

    private String sign(String orderInfo) {
        try {
            PKCS8EncodedKeySpec priPKCS8 = new PKCS8EncodedKeySpec(Base64.decode(Keys.PRIVATE));
            KeyFactory keyf = KeyFactory.getInstance(ALGORITHM);
            PrivateKey priKey = keyf.generatePrivate(priPKCS8);
            java.security.Signature signature = java.security.Signature
                    .getInstance(SIGN_ALGORITHMS);
            signature.initSign(priKey);
            signature.update(orderInfo.getBytes(DEFAULT_CHARSET));
            byte[] signed = signature.sign();
            return Base64.encode(signed);
        } catch (NoSuchAlgorithmException | InvalidKeySpecException | InvalidKeyException | UnsupportedEncodingException | SignatureException e) {
            e.printStackTrace();
        }
        return null;
    }

    private String createAlipayInfo(String orderNumber, String name, String introduction, String price) {
        AlipayOrderInfoBuilder builder = new AlipayOrderInfoBuilder();
        builder.setOutTradeNo(orderNumber);
        builder.setSubject(name);
        builder.setBody(introduction);
//        String price = UseUtil.handlePrice(Double.parseDouble(priceCountTxt.getText().toString()));
        builder.setTotalFee(price);
        String url = PropertiesUtil.getAlipayNotifyUrl();
        builder.setNotifyUrl(url);
        return builder.build();
    }

    private class AlipayRunnable implements Runnable {

        @Override
        public void run() {
            // 构造PayTask 对象
            PayTask alipay = new PayTask(activity);
            // 调用支付接口
            try {
                String result = alipay.pay(payInfo);
                Message msg = new Message();
                msg.what = MESSAGE_ALIPAY;
                msg.obj = result;
                mAlipayHandler.sendMessage(msg);
            } catch (Exception e) {
                Log.d("test", e.toString());
            }
        }
    }

    Handler mAlipayHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            Result result = new Result((String) msg.obj);
            switch (msg.what) {
                case MESSAGE_ALIPAY:
                    String resultStatus = result.resultStatus;

                    // 判断resultStatus 为"9000"则代表支付成功，具体状态码代表含义可参考接口文档
                    if (TextUtils.equals(resultStatus, "9000")) {
                        if (mResult) {//C端支付
                            customerPayActivity = new CustomerPayActivity();
                            customerPayActivity.confirmOreder(orderId,couponModelId,word,UserInfoKeeper.readPhoneNumber(activity),true);
                        } else {
                            showDialog(mResult);
                        }
                        ToastUtil.showShort(activity, "支付成功");
                    } else {
                        // 判断resultStatus 为非"9000"则代表可能支付失败
                        // "8000" 代表支付结果因为支付渠道原因或者系统原因还在等待支付结果确认，最终交易是否成功以服务端异步通知为准（小概率状态）
                        if (TextUtils.equals(resultStatus, "8000")) {
                            ToastUtil.showShort(activity, "支付结果确认中");
                        } else {
                            ToastUtil.showShort(activity, "支付失败");
                        }
                    }
                    break;
                default:
                    break;
            }
        }
    };

    public String getSignType() {
        return "sign_type=\"RSA\"";
    }
    //支付宝支付END

    //弹出购买成功券包
    BaseAnimatorSet bas_in = new FlipVerticalSwingEnter();
    BaseAnimatorSet bas_out = new FadeExit();

    private void showDialog(final boolean result) {
        String title = activity.getResources().getString(R.string.dialog_success_buy_B);
        String message = activity.getResources().getString(R.string.dialog_my_tickets);
        final NormalTipDialog dialog = new NormalTipDialog(activity);
        dialog.content(title)//
                .isTitleShow(false)
                .btnText(message)//
                .showAnim(bas_in)//
                .dismissAnim(bas_out)//
                .show();
        dialog.setOnBtnClickL(new OnBtnClickL() {
            @Override
            public void onBtnClick() {
                Intent intent = new Intent(activity, MyOrderActivity.class);
                activity.startActivity(intent);
                dialog.dismiss();
            }
        });
    }
}
